#!/bin/bash

echo "=========================================="
echo "   Demo Survey 后台运行脚本"
echo "=========================================="
echo

# 检查screen是否安装
if ! command -v screen &> /dev/null; then
    echo "Screen未安装，使用nohup方式运行..."
    USE_SCREEN=false
else
    echo "使用Screen方式运行..."
    USE_SCREEN=true
fi

# 检查并终止占用端口的进程
echo "1. 检查并终止占用端口的进程..."
if lsof -Pi :13000 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "终止占用端口13000的进程..."
    lsof -Pi :13000 -sTCP:LISTEN -t | xargs kill -9 2>/dev/null
fi

if lsof -Pi :8081 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "终止占用端口8081的进程..."
    lsof -Pi :8081 -sTCP:LISTEN -t | xargs kill -9 2>/dev/null
fi

echo
echo "2. 安装Python依赖..."
pip install -r requirements.txt

echo
echo "3. 启动后端服务..."
if [ "$USE_SCREEN" = true ]; then
    # 使用screen方式
    screen -dmS demosurvey-backend bash -c 'python main.py'
    echo "后端已在screen会话 'demosurvey-backend' 中启动"
else
    # 使用nohup方式
    nohup python main.py > backend.log 2>&1 &
    BACKEND_PID=$!
    echo "后端进程ID: $BACKEND_PID"
fi

echo
echo "4. 等待后端启动..."
sleep 5

echo
echo "5. 启动前端服务..."
if [ "$USE_SCREEN" = true ]; then
    # 使用screen方式
    screen -dmS demosurvey-frontend bash -c 'npm run serve'
    echo "前端已在screen会话 'demosurvey-frontend' 中启动"
else
    # 使用nohup方式
    nohup npm run serve > frontend.log 2>&1 &
    FRONTEND_PID=$!
    echo "前端进程ID: $FRONTEND_PID"
fi

echo
echo "=========================================="
echo "系统已在后台启动！"
echo
echo "访问地址:"
echo "前端地址: http://localhost:8081"
echo "后端API: http://localhost:13000"
echo "API文档: http://localhost:13000/docs"
echo

if [ "$USE_SCREEN" = true ]; then
    echo "Screen会话管理:"
    echo "查看所有会话: screen -ls"
    echo "连接后端会话: screen -r demosurvey-backend"
    echo "连接前端会话: screen -r demosurvey-frontend"
    echo "退出会话: Ctrl+A, D"
    echo "终止会话: screen -S demosurvey-backend -X quit"
    echo "           screen -S demosurvey-frontend -X quit"
else
    echo "进程管理:"
    echo "后端PID: $BACKEND_PID"
    echo "前端PID: $FRONTEND_PID"
    echo "停止服务: kill $BACKEND_PID $FRONTEND_PID"
    echo "查看日志: tail -f backend.log"
    echo "         tail -f frontend.log"
fi

echo "=========================================="